import axios from 'axios'
import store from "@/store/index"
import router from "@/router/index"

const instance = axios.create({
    timeout: 5000,
    baseURL: 'http://localhost:8080'
});

instance.interceptors.request.use((config) => {
    if (store.state.token) {
        config.headers.Authorization = store.state.token;
    }
    return config;
});

instance.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        //默认除了2XX之外的都是错误的，就会走这里
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    router.replace({
                        path: "login",
                        query: { redirect: router.currentRoute.fullPath }, // 将跳转的路由path作为参数，登录成功后跳转到该路由
                    });
            }
        }
        return Promise.reject(error.response);
    }
);
export default instance
